<?php

	class AKB_RSS
	{
		var $_catId = 0;
		var $max = 50;
		var $defaultLimit = 10;

		/**
		* Constructor
		* Initialise any variables required for this class
		*
		* @return void
		*/
		function AKB_RSS()
		{
			// Get the category (if any)
			$this->_SetCat();
		}

		/**
		* _GetCat
		* Return the current category id
		*
		* @return int
		*/
		function _GetCat()
		{
			return $this->_catId;
		}

		/**
		* _SetCat
		* Set the category id
		*
		* @return void
		*/
		function _SetCat()
		{
			if (isset($_GET['c'])) {
				$this->_catId = (int)$_GET['c'];
			}
		}

		/**
		* _GetCatName
		* Get the category name for the current category id
		*
		* @return string
		*/
		function _GetCatName()
		{
			if (empty($GLOBALS['AKB_CLASS_HELPER']->catsById)) {
				$GLOBALS['AKB_CLASS_HELPER']->getCatsInfo();
			}
			return $GLOBALS['AKB_CLASS_HELPER']->catsById[$this->_GetCat()]['name'];
		}

		/**
		* HandlePage
		* The default page handler
		*
		* @return void
		*/
		function HandlePage()
		{
			$valid_types = array (
				'category',
				'recent',
				'popular',
				'featured',
				'news',
			);

			// If the type isn't set explicitly, set it to a category
			if (!isset($_GET['t'])) {
				$_GET['t'] = 'category';
			}

			if (!in_array($_GET['t'], $valid_types)) {
				echo '';
				die();
			}

			// Make sure the limit is a number and isnt too low
			if (!isset($_GET['num']) || !is_numeric($_GET['num']) || $_GET['num'] < 1 ) {
				$_GET['num'] = $this->defaultLimit;
			}

			// Make sure the limit isn't too high
			if ($_GET['num'] > $this->max) {
				$_GET['num'] = $this->max;
			}

			$this->GetRSS();

		}

		/**
		* GetAuth
		* Get the authorisation information for either this->_catId if $catid is
		* null (default) or the catid passed in
		*
		* @param mixed $catid The id of the cat to get auth info about
		*
		* @return array array(pass, catid) of the cat in the tree whos auth
		* applies to the given $catid
		*/
		function GetAuth($catid=null)
		{
			$h = $GLOBALS['AKB_CLASS_HELPER'];
			if ($catid === null) {
				$cat = $h->catsById[$this->_catId];
			} else {
				$cat = $h->catsById[$catid];
			}

			// If this is a non-root category and this category doesn't have
			// a password, check the parent for a password
			if ($cat['parentid'] > 0 &&  trim($cat['pass']) == '' ) {
				return $this->GetAuth($cat['parentid']);
			} else {
				return array($cat['pass'], $cat['categoryid']);
			}
		}

		/**
		* GetRSS
		* Display the actual rss feed
		*
		* @return void
		*/
		function GetRSS()
		{
			$query = '';
			$output = '';
			$GLOBALS['Catname'] = '';
			$workflowQry = '';
			if (validUrl()) {
				$workflowQry = 'AND (q.workflowstatus = \''.WF_STATUS_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_AUTO_APPROVED.'\' OR q.workflowstatus = \''.WF_STATUS_REPENDING.'\' '.getShowDisapprovedArticleString('OR', 'q.').') ';

			}
			
			switch ($_GET['t']) {
				case 'category':
					$GLOBALS['Catname'] = htmlspecialchars($this->_GetCatName(), ENT_QUOTES, $GLOBALS['charset']);
					if ($this->_GetCat() != 0) {
						
						$acccessible_cats = $GLOBALS['AKB_CLASS_HELPER']->getAccessibleCats();

						$categoryRestrictSQL = "";
						if (isset($GLOBALS['categoryRestrictOption']) && $GLOBALS['categoryRestrictOption'] == "1") {
							$accessible_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
							$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
						}							
						
						$query = '
							SELECT DISTINCT '.$GLOBALS['AKB_DB']->Concat('firstname', "' '", 'lastname').' as author, q.questionid, title, answer, lastupdated, c.categoryid, workflowstatus';
						$query = 'SELECT q.questionid
							FROM 
								'.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'catassoc_history ca, '.$GLOBALS['tablePrefix'].'categories c, 
								('.$GLOBALS['tablePrefix'].'question_auth qa	RIGHT JOIN '.$GLOBALS['tablePrefix'].'questions q ON qa.questionid = q.questionid)

							WHERE q.questionid = a.questionid
							AND c.categoryid = a.categoryid
							AND ca.categoryid = a.categoryid
							AND ca.questionid = a.questionid
							AND a.categoryid = '.$this->_GetCat().'
							AND u.userid = q.userid
							AND visible=1
							'.$workflowQry.'
							AND 
								(
								((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND ((q.enableexpiry = 1) AND q.expirydate > \''.$GLOBALS['currDatetime'].'\'))
								OR
								((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND (q.enableexpiry = 0))
								)
							AND (qa.groupid IS NULL '.AKB_AUTH::deriveGroupSQL().') 
							GROUP BY q.questionid';
						
							$result = $GLOBALS['AKB_DB']->Query($query);
							while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
								$questionids[] = $row['questionid'];
							}
							$query = 'SELECT '.$GLOBALS['AKB_DB']->Concat('firstname', "' '", 'lastname').' as author, q.questionid, title, answer, lastupdated, workflowstatus
							FROM '.$GLOBALS['tablePrefix'].'questions q, '.$GLOBALS['tablePrefix'].'users u
							WHERE u.userid = q.userid
							AND q.questionid IN ('.implode(',', $questionids).')
							ORDER BY lastupdated DESC, q.title ASC
							';
					}
				break;
				case 'recent':
					$GLOBALS['Catname'] = GetLang('hpRecentQuestions');

					$acccessible_cats = $GLOBALS['AKB_CLASS_HELPER']->getAccessibleCats();

					// We break this function up into 2 queries because doing
					// it all in one query for a 50,000 question system takes
					// about 13 seconds but doing 2 queries less than 1 second
					// for the two combined
					
					$acccessible_cats = $GLOBALS['AKB_CLASS_HELPER']->getAccessibleCats();

					$categoryRestrictSQL = "";
					if (isset($GLOBALS['categoryRestrictOption']) && $GLOBALS['categoryRestrictOption'] == "1") {
						$accessible_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
						$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
					}					
					
					$query = 'SELECT q.questionid
					FROM 
					
					'.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'categories c,
					('.$GLOBALS['tablePrefix'].'question_auth qa	RIGHT JOIN '.$GLOBALS['tablePrefix'].'questions q ON qa.questionid = q.questionid)

					WHERE q.questionid = a.questionid
					AND a.categoryid = c.categoryid
					AND visible=1
					'.$workflowQry.'
					AND
						(
						((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND ((q.enableexpiry = 1) AND q.expirydate >\''.$GLOBALS['currDatetime'].'\'))
						OR
						((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND (q.enableexpiry = 0))
						)			
					'.$categoryRestrictSQL.'
					AND (qa.groupid is null '.AKB_AUTH::deriveGroupSQL().') 
					GROUP BY q.questionid, q.lastupdated
					ORDER BY  q.lastupdated DESC
					'.$GLOBALS['AKB_DB']->AddLimit(0, (int)$_GET['num']);

					$result = $GLOBALS['AKB_DB']->Query($query);
					while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
						$questionids[] = $row['questionid'];
					}
					
					$query = 'SELECT '.$GLOBALS['AKB_DB']->Concat('firstname', "' '", 'lastname').' as author, q.questionid, title, answer, lastupdated, workflowstatus
					FROM '.$GLOBALS['tablePrefix'].'questions q, '.$GLOBALS['tablePrefix'].'users u
					WHERE u.userid = q.userid
					AND q.questionid IN ('.implode(',', $questionids).')
					ORDER BY lastupdated DESC
					'.$GLOBALS['AKB_DB']->AddLimit(0, $_GET['num']);
					
					
				break;
				case 'popular':
					if ($this->_GetCat() != 0) {
						$GLOBALS['Catname'] = htmlspecialchars($this->_GetCatName(), ENT_QUOTES, $GLOBALS['charset']);
					} else {
						$GLOBALS['Catname'] = GetLang('hpMostPopularQuestions');
					}
					
					if ($this->_GetCat()) {
						$catFilter = $GLOBALS['AKB_CLASS_HELPER']->tree->GetBranchFrom($this->_GetCat(), false);
						if ($catFilter) {
							array_push($catFilter,$this->_GetCat());
						}
					} else {
						$catFilter = false;
					}
					
					$categoryRestrictSQL = "";
					if (isset($GLOBALS['categoryRestrictOption']) && $GLOBALS['categoryRestrictOption'] == "1") {
						$accessible_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
						
						if ($catFilter) {
							$accessible_cats = array_intersect($accessible_cats,$catFilter);
						}
						
						$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
						
					} else if ($catFilter) {
						$perm_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
						$accessible_cats = array_intersect($perm_cats,$catFilter);
						$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
					}

					$query = '
						SELECT q.questionid, title, '.$GLOBALS['AKB_DB']->Concat('firstname', "' '", 'lastname').' as author, lastupdated, answer, workflowstatus
						FROM '.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'questions q 
						WHERE u.userid = q.userid
						AND q.questionid IN
						(
						SELECT DISTINCT q.questionid
						FROM 
							'.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'categories c, 
							('.$GLOBALS['tablePrefix'].'question_auth qa RIGHT JOIN '.$GLOBALS['tablePrefix'].'questions q ON qa.questionid = q.questionid)

						WHERE q.questionid = a.questionid
						AND a.categoryid = c.categoryid
						AND u.userid = q.userid
						AND score > 0
						AND visible=1
						'.$workflowQry.'
						AND 
							(
							((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND ((q.enableexpiry = 1) AND q.expirydate > \''.$GLOBALS['currDatetime'].'\'))
							OR
							((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND (q.enableexpiry = 0))
							)
						'.$categoryRestrictSQL.'
						AND (qa.groupid is null '.AKB_AUTH::deriveGroupSQL().') 
						)
						ORDER BY score DESC
					'.$GLOBALS['AKB_DB']->AddLimit(0, (int)$_GET['num']);
				break;
				case 'news':
					$GLOBALS['Catname'] = GetLang('hpNewsQuestions');
					// Get a list of visible News item sorted by score
					$query  = 'SELECT n.newsid, n.title, '.$GLOBALS['AKB_DB']->Concat('u.firstname', "' '", 'u.lastname').' as author, n.lastupdated, n.content as answer ';
					$query .= "FROM ".$GLOBALS['tablePrefix']."newss n, ".$GLOBALS['tablePrefix']."users u ";
					$query .= "WHERE 1=1 ";
					$query .= "AND n.userid = u.userid ";
					$query .= "AND n.visible = 1 ";
					$query .= "ORDER BY n.lastupdated DESC ";
					$query .= $GLOBALS['AKB_DB']->AddLimit(0, (int)$_GET['num']);
				break;
				case 'featured':
					if ($this->_GetCat() != 0) {
						$GLOBALS['Catname'] = htmlspecialchars($this->_GetCatName(), ENT_QUOTES, $GLOBALS['charset']);
					} else {
						$GLOBALS['Catname'] = GetLang('hpFeaturedQuestions');
					}
					
					if ($this->_GetCat()) {
						$catFilter = $GLOBALS['AKB_CLASS_HELPER']->tree->GetBranchFrom($this->_GetCat(), false);
						if ($catFilter) {
							array_push($catFilter,$this->_GetCat());
						}
					} else {
						$catFilter = false;
					}
					
					$categoryRestrictSQL = "";
					if (isset($GLOBALS['categoryRestrictOption']) && $GLOBALS['categoryRestrictOption'] == "1") {
						$accessible_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
						
						if ($catFilter) {
							$accessible_cats = array_intersect($accessible_cats,$catFilter);
						}
						
						$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
						
					} else if ($catFilter) {
						$perm_cats = $GLOBALS['AKB_CLASS_HELPER']->GetPermittedCats();
						$accessible_cats = array_intersect($perm_cats,$catFilter);
						$categoryRestrictSQL = "AND c.categoryid IN (".implode(", ", $accessible_cats).")";
					}

					$query = '
						SELECT q.questionid, title, '.$GLOBALS['AKB_DB']->Concat('firstname', "' '", 'lastname').' as author, lastupdated, answer, workflowstatus
						FROM '.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'questions q 
						WHERE u.userid = q.userid
						AND q.questionid IN
						(
						SELECT DISTINCT q.questionid
						FROM 
							'.$GLOBALS['tablePrefix'].'users u, '.$GLOBALS['tablePrefix'].'categoryassociations a, '.$GLOBALS['tablePrefix'].'categories c, 
							('.$GLOBALS['tablePrefix'].'question_auth qa RIGHT JOIN '.$GLOBALS['tablePrefix'].'questions q ON qa.questionid = q.questionid)

						WHERE q.questionid = a.questionid
						AND a.categoryid = c.categoryid
						AND u.userid = q.userid
						AND featured = 1
						'.$workflowQry.'
						AND visible=1
						AND 
							(
							((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND ((q.enableexpiry = 1) AND q.expirydate > \''.$GLOBALS['currDatetime'].'\'))
							OR
							((q.startdate < \''.$GLOBALS['currDatetime'].'\') AND (q.enableexpiry = 0))
							)
						'.$categoryRestrictSQL.'
						AND (qa.groupid is null '.AKB_AUTH::deriveGroupSQL().') 
						)
						ORDER BY score DESC
					'.$GLOBALS['AKB_DB']->AddLimit(0, (int)$_GET['num']);
				break;
			}

			if (empty($query)) {
				echo '';
				die();
			}

			ob_end_clean();
			header('Content-Type: text/xml; charset='.$GLOBALS['charset']);

			$GLOBALS['KbName'] = $this->CleanString($GLOBALS['knowledgebaseName']);
			$GLOBALS['GenDate'] = date('D, d M Y H:i:s T');

			$output = $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RssFeedHeader');

			$result = $GLOBALS['AKB_DB']->Query($query);
			if ($GLOBALS['AKB_DB']->CountResult($query) > 0) {
				$tmpRow = array();
				$historyQuestionIds = array();
				$validStatus = getShowDisapprovedArticleArray();
				while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
					if (validUrl() && isset($row['workflowstatus'])) {
						if (!in_array($row['workflowstatus'], $validStatus)) {
							$tmpRow[] = $row;
						} else {
							$row['title'] = '';
							$tmpRow[] = $row;
							$historyQuestionIds[] = trim($row['questionid']);
						}
					} else {
						$tmpRow[] = $row;
					}
				}
				
				if (sizeof($historyQuestionIds)) {
					$historyQuestionIdsStr = "'" . implode("','", $historyQuestionIds) . "'";
					$historyQuestionIdsQry = "SELECT qh.questionid, qh.title, qh.answer 
					FROM {$GLOBALS['tablePrefix']}questions_history qh, {$GLOBALS['tablePrefix']}catassoc_history c, {$GLOBALS['tablePrefix']}categoryassociations ca 
					WHERE (qh.workflowstatus = '".WF_STATUS_AUTO_APPROVED."' OR qh.workflowstatus = '".WF_STATUS_APPROVED."')
					AND qh.questionid = c.questionid 
					AND c.questionid = ca.questionid 
					AND c.categoryid = ca.categoryid 
					AND qh.questionid IN ($historyQuestionIdsStr)
					$categoryRestrictSQL
					ORDER BY qh.lastupdated ASC
					";
					$historyQuestionIdsQryRes = $GLOBALS['AKB_DB']->Query($historyQuestionIdsQry);
					$historyQuestion = array();
					if ($GLOBALS['AKB_DB']->CountResult($historyQuestionIdsQry) > 0) {
						while ($row = $GLOBALS['AKB_DB']->Fetch($historyQuestionIdsQryRes)) {
							$historyQuestion[$row['questionid']] = $row;
						}
					}
				}
					
				foreach ($tmpRow as $row) {
					if ($_GET['t'] != 'news') {
						if (isset($historyQuestion[$row['questionid']])) {
							$row['title'] = $historyQuestion[$row['questionid']]['title'];
							$row['answer'] = $historyQuestion[$row['questionid']]['answer'];
						}
					}
					if ($row['title'] != '') {
						$GLOBALS['Title']		= htmlspecialchars($row['title'], ENT_QUOTES, $GLOBALS['charset']);
						$GLOBALS['Author']		= htmlspecialchars($row['author'], ENT_QUOTES, $GLOBALS['charset']);
						$GLOBALS['PubDate']		= date('D, d M Y H:i:s \G\M\T', strtotime($row['lastupdated']) - (int) date('Z'));
						if ($_GET['t'] == 'news') {
							$GLOBALS['Link']		= GetUrl('news', $row['newsid']);
						} else {
							$GLOBALS['Link']		= GetUrl('question', $row['questionid']);
						}
		
						$answer = $row['answer'];
		
						$answer = str_replace('&nbsp;', ' ', $answer);
						$answer = preg_replace('%<(style|script).*?</\1>%si', '', $answer);
						$GLOBALS['Description']	= $this->CleanString(ellipsize(strip_tags($answer), 200));
						$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RssFeedRow');
					}
				}
			}

			$output .= $GLOBALS['AKB_CLASS_TEMPLATE']->GetSnippet('RssFeedFooter');

			echo $output;
			if ($result) {
				$GLOBALS['AKB_DB']->FreeResult($result);
			}
			die();
		}

		/**
		* CleanString
		*
		* Cleans a string for inclusion in an rss feed
		*
		* @param string $str The string to clean
		*
		* @return string The cleaned up string
		*/
		function CleanString($str)
		{
			return htmlspecialchars($str, ENT_QUOTES, $GLOBALS['charset']);
		}

	}

?>
